import React, { useEffect, useRef, useState } from 'react'
import {
 Button, message, notification, Popconfirm,
} from 'antd'
import { connect } from '@umijs/max'
import list2tree from 'list2tree'
import {
  BreadcrumbBar,
  InputSearch,
  ProTable,
  ProTableOperate,
  ProTableOptions,
  ProTree,
  searchTreeListByName,
} from '@/components'
import Tools from '@/utils/Tools'
import { ClickImport, CreateStandard } from './page-components'
import styles from './index.less'

const { OperateItem } = ProTableOperate

const menus = [{ name: '标准设计' }, { name: '标准定义' }]

const getNavTreeDataFunc = list2tree({
  idKey: 'id',
  parentIdKey: 'pid',
  newKey: {
    key: 'id',
    value: 'id',
    title: 'themeName',
  },
})

// 获取该id下所有的子id
const getAllChildrenId = (dataRef) => {
  const tempArr = [dataRef.id]
  if (dataRef.children) {
    dataRef.children.map((item) => {
      // eslint-disable-next-line prefer-spread
      tempArr.push.apply(tempArr, getAllChildrenId(item))
    })
  }
  return tempArr
}

const StandardDefine = (props) => {
  const [treeData, setTreeData] = useState([])
  const [treeDataNew, setTreeDataNew] = useState([])
  const [selectedKeys, setSelectedKeys] = useState([])
  const [query, setQuery] = useState({})
  const [inpValue, setInpValue] = useState('')
  const [forceUpdate, setForceUpdate] = useState(0)
  // const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [loading, setLoading] = useState(false)
  const [optTypeParams, setOptTypeParams] = useState(null)
  const createStandardRef = useRef()
  const clickImportRef = useRef()
  const tableRef = useRef()
  let tree

  useEffect(() => {
    getTreeThemes()
  }, [])

  useEffect(() => {
    if (inpValue === '') {
      fetchData()
    }
  }, [inpValue])

  // 获取左侧列表方法
  const getTreeThemes = () => {
    // 标记每个节点是第几层children
    const signLayerNum = (item, num = 0) => {
      item.layerNum = num
      if (num >= 5) {
        item.icon = true
      }
      item?.children?.map((child) => {
        const tempNum = num + 1
        signLayerNum(child, tempNum)
        return null
      })
    }
    props.dispatch({
      type: 'standardDefine/dictionaryGroupList',
      cb: (data) => {
        const arr = getNavTreeDataFunc(data) || []
        // 给tree的数据标上第几层children
        arr.map((item) => {
          signLayerNum(item)
          return null
        })
        setTreeData(data || [])
        setTreeDataNew(arr)
      },
    })
  }

  const columns = [
    {
      title: '中文名称',
      dataIndex: 'dictNameCn',
      key: 'dictNameCn',
      width: '15%',
    },
    {
      title: '英文名称',
      dataIndex: 'dictNameEn',
      key: 'dictNameEn',
      width: '15%',
      sorter: true,
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '标准目录',
      dataIndex: 'dictDirName',
      key: 'dictDirName',
      width: '10%',
      render: (text) => (!text || text === '' ? '--' : text),
    },
    {
      title: '状态',
      dataIndex: 'releaseStatus',
      key: 'releaseStatus',
      width: '13%',
      render: (releaseStatus) => (
        releaseStatus === 0 ? (
          <>
            <i className="iconfont icon-daiban hu-blue" />
            待发布
          </>
        ) : (
          <>
            <i className="iconfont icon-chenggong hu-green" />
            已发布
          </>
        )
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTimeUnix',
      key: 'updateTimeUnix',
      width: '15%',
      sorter: true,
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      key: 'createUserName',
      width: '10%',
    },
    {
      title: '操作',
      // dataIndex: 'space',
      key: 'operate',
      render: (record) => {
        const { releaseStatus, id } = record
        return (
          <ProTableOptions>
            {(releaseStatus === 0 || null) && <span onClick={() => { dictionaryRelease(id, 1) }}>发布</span>}
            {(releaseStatus === 0 || null) && <span onClick={() => { dictionaryDetail(id, 0) }}>编辑</span>}
            {(releaseStatus === 1 || null) && <span onClick={() => { dictionaryRelease(id, 0) }}>下线</span>}
            {(releaseStatus === 1 || null) && <span onClick={() => { dictionaryDetail(id, true) }}>查看</span>}
            {
              (releaseStatus === 0 || null) && (
                <Popconfirm
                  title="确认要删除吗？"
                  onConfirm={() => { dictionaryDelete(id) }}
                  okText="确定"
                  cancelText="取消"
                >
                  <span>删除</span>
                </Popconfirm>
              )
            }
          </ProTableOptions>
        )
      },
    },
  ]

  // 删除标准
  const dictionaryDelete = (id) => {
    setLoading(true)
    props.dispatch({
      type: 'standardDefine/dictionaryDelete',
      params: {
        id,
      },
      cb: (data) => {
        setLoading(false)
        if (data) {
          forceUpdateFn()
        }
      },
    })
  }

  // 发布或下线标准
  const dictionaryRelease = (id, releaseStatus) => {
    setLoading(true)
    props.dispatch({
      type: 'standardDefine/dictionaryRelease',
      params: {
        id,
        releaseStatus,
      },
      cb: (data) => {
        setLoading(false)
        if (data) {
          forceUpdateFn()
        }
      },
    })
  }

  // 查看标准详情
  const dictionaryDetail = (id, disabled) => {
    setLoading(true)
    props.dispatch({
      type: 'standardDefine/dictionaryDetail',
      params: {
        id,
      },
      cb: (data) => {
        setLoading(false)
        createStandardRef?.current?.toggleModal(data, disabled)
      },
    })
  }

  const onSelect = (selectedKeysParams, node) => {
    setSelectedKeys(getAllChildrenId(node.node))
    // 重置表格选中的数据
    tableRef?.current?.resetSelectedRowKeys()
    tableRef?.current?.resetPageNum()
    setQuery({
      ...query,
      dictDirIds: getAllChildrenId(node.node).join(','),
    })
  }

  const fetchData = () => {
    const tempQuery = {}
    tempQuery.search = inpValue
    setQuery({
      ...query,
      ...tempQuery,
      dictDirIds: selectedKeys.join(','),
    })
  }

  const forceUpdateFn = () => {
    setForceUpdate(forceUpdate + 1)
    getTreeThemes()
  }

  // 批量操作 optType: 发布为0，删除为1，下线为2
  const batchOpt = (argu, optType) => {
    if (argu.length < 1) {
      message.warning('请至少选择一条数据')
      return null
    }

    setLoading(true)
    setOptTypeParams(optType)

    props.dispatch({
      type: 'standardDefine/batchOpt',
      params: {
        optType,
        ids: argu,
      },
      cb: (data) => {
        setLoading(false)
        setOptTypeParams(null)
        const { status, msg = '服务端错误' } = data
        if (status === 200) {
          message.success('操作成功')
          // setSelectedRowKeys([])
          tableRef?.current?.resetSelectedRowKeys()
          forceUpdateFn()
        } else {
          notification.error({
            message: '操作失败',
            description: msg,
          })
        }
      },
    })
    return null
  }

  // 批量导出
  const onExport = () => {
    const selectedRowKeys = tableRef?.current?.state.selectedRowKeys
    if (selectedRowKeys.length < 1) {
      message.warning('请至少选择一条数据')
      return null
    }
    let idsStr = ''
    selectedRowKeys.map((item) => {
      if (idsStr !== '') idsStr += ','
      idsStr += item
      return null
    })
    // window.location.href = `/api/v1/dictionary/export/list?ids=${idsStr}`
    Tools.downloadFile(`${window.suanpan}/api/v1/dictionary/export/list?ids=${idsStr}`)
    return null
  }

  const rowSelection = {
    type: 'checkbox',
  }

  return (
    <div className={styles.standard_define}>
      <BreadcrumbBar menu={menus} />
      <div className={styles.page_content}>
        <div className={styles.page_content_left}>
          <ProTree
            showLine
            showSearch
            width={208}
            showTitle={false}
            treeData={treeDataNew}
            selectedKeys={selectedKeys}
            onSelect={onSelect}
            ref={(dev) => (tree = dev)}
            search={(name) => {
              const searchTree = searchTreeListByName(
                name,
                treeData,
                'themeName',
              )
              const treeDataNews = getNavTreeDataFunc(
                searchTree.result,
              )
              setTreeDataNew(treeDataNews)
              tree.onExpand(searchTree.fatchIds)
            }}
          />
        </div>
        <div className={styles.page_content_right}>
          <ProTableOperate>
            <OperateItem align="left">
              <InputSearch
                placeholder="请输入中文名称或英文名称进行搜索"
                value={inpValue}
                onChange={(e) => {
                  setInpValue(e.target.value)
                }}
                onSearch={fetchData}
              />
            </OperateItem>
            <OperateItem itemType="btn">
              <Button onClick={onExport}>批量导出</Button>
              <Button
                onClick={() => {
                  clickImportRef?.current?.toggleModal()
                }}
              >
                一键导入
              </Button>
              <Button
                type="primary"
                onClick={() => {
                  createStandardRef?.current?.toggleModal()
                }}
              >
                新建标准
              </Button>
            </OperateItem>
          </ProTableOperate>
          <ProTable
            ref={tableRef}
            // spinning={false}
            loading={loading}
            key={forceUpdate}
            url="/api/v1/dictionary/list"
            query={query}
            rowKey="id" // key传递的是否有效，影响rowSelection的使用
            columns={columns}
            rowSelection={rowSelection}
            // clickCheckBox={clickCheckBox}
            bulkOperation={[
              {
                title: '批量发布',
                loading: optTypeParams === 0 ? loading : false,
                onClick: (params) => { batchOpt(params, 0) },
              },
              {
                title: '批量下线',
                loading: optTypeParams === 2 ? loading : false,
                onClick: (params) => { batchOpt(params, 2) },
              },
              {
                title: '批量删除',
                loading: optTypeParams === 1 ? loading : false,
                onClick: (params) => { batchOpt(params, 1) },
              },
            ]}
          />
        </div>
      </div>

      <CreateStandard
        ref={createStandardRef}
        forceUpdateFn={forceUpdateFn}
      />
      <ClickImport
        ref={clickImportRef}
        forceUpdateFn={forceUpdateFn}
      />
    </div>
  )
}

export default connect(({ standardDefine }) => ({ ...standardDefine }))(StandardDefine)
